var http = require('http')
var url = require('url')
var fs = require('fs')
var template = require('art-template')
var comments = [{
        name: '张三',
        message: '今天天气不错！',
        dateTime: '2015-10-16'
    },
    {
        name: '张三2',
        message: '今天天气不错！',
        dateTime: '2015-10-16'
    },
    {
        name: '张三3',
        message: '今天天气不错！',
        dateTime: '2015-10-16'
    },
    {
        name: '张三4',
        message: '今天天气不错！',
        dateTime: '2015-10-16'
    },
    {
        name: '张三5',
        message: '今天天气不错！',
        dateTime: '2015-10-16'
    }
]
var server = http.createServer()
server.on('request', function (req, res) {

    var parseObj = url.parse(req.url, true)
    var pathname = parseObj.pathname
    var query = parseObj.query
    console.log(pathname)
    if (pathname === '/') {
        fs.readFile('./index.html', function (err, data) {
            if (err) {
                return res.end('404 Not Found.')
            }
            var htmlStr = template.render(data.toString(), {
                comments: comments
            })
            res.end(htmlStr)
        })
        // res.end(`
        // <!DOCTYPE html>
        // <html lang="en">
        //   <head>
        //     <meta charset="UTF-8" />
        //     <title>Document</title>
        //   </head>
        // <body>
        //   <h4>hello Express！你好</h4>
        // </body>
        // </html> 
        // `)
    } else if (pathname === '/post') {
        fs.readFile('./post.html', function (err, data) {
            if (err) {
                return res.end('404 Not Found')
            } else {
                res.end(data)
            }
        })
    } else if (pathname === '/pinglun') {
        var newComment = query
        var DateNow = new Date().toLocaleDateString()
        newComment.dateTime = DateNow;
        comments.unshift(newComment)
        console.log(comments)
        res.statusCode = 302
        res.setHeader('Location', '/')
        res.end()
    } else if (pathname === '/write') {
        res.setHeader('Content-Type', 'text/plain; charset=utf-8')
        fs.writeFile('./write.html', '我是写入文件', function (err) {
            if (err) {
                res.end('404')
            } else {

                fs.readFile('./write.html', function (err, data) {
                    if (err) {
                        res.end('404')
                    } else {
                        res.end(data)
                    }
                })
                res.end('写入成功')
            }
        })
    } else if (pathname === '/readdir') {
        fs.readdir('C:/Users/蔡蓓娟/Desktop/03', function (err, file) {
            if (err) {
                return console.log('目录不存在')
            } else {
                console.log(file)

            }
        })
    }

    // res.send(parseObj)
    // res.end('parseObj')
})

server.listen(9000, 'localhost', function () {
    console.log('running at loacalhost')
})